<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        border: solid;
        width: 600px;
        height: 600px;
        margin: 100px auto auto 100px;
        position: relative;
      }

      #ball {
        width: 100px;
        height: 100px;
        background-color: blueviolet;
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div id="box">
      <div id="ball"></div>
    </div>
    <script>
      const box = document.getElementById("box");
      const ball = document.getElementById("ball");

      const { x, y } = box.getBoundingClientRect();

      ball.onmousedown = function (be) {
        // 计算出需要减去的宽度
        const bc = ball.getBoundingClientRect();
        const w = be.clientX - bc.x;
        const h = be.clientY - bc.y;

        // 触发 box.onmousemove 事件
        box.onmousemove = function (e) {
          // 鼠标相对于box坐标
          const bx = e.clientX - x - w;
          const by = e.clientY - y - h;
          // ball跟随鼠标在box中移动
          ball.style.left = bx + "px";
          ball.style.top = by + "px";
        };
      };

      ball.onmouseup = function () {
        box.onmousemove = null;
      };
    </script>
  </body>
</html>
